package org.aplikator.server.descriptor;

import org.aplikator.server.Context;
import org.aplikator.server.DescriptorRegistry;
import org.aplikator.server.util.Configurator;

import java.util.Locale;
import java.util.UUID;

public abstract class ServerDescriptorBase {

    protected static final char TYPE_DELIMITER = ':';
    protected static final char SUFFIX_DELIMITER = '_';
    protected static final char PATH_DELIMITER = '.';

    protected ServerDescriptorBase(String id) {
        if (id == null) {
            this.id = getIdClassPrefix() + UUID.randomUUID().toString();
        } else {
            this.id = getIdClassPrefix() + id;
        }
        // throws Illegal Argument Exception for duplicate IDs
        DescriptorRegistry.get().registerDescriptionItem(this);
    }

    private String getIdClassPrefix(){
        if (this instanceof Entity){
            return "";
        }else{
            return getClass().getSimpleName() + TYPE_DELIMITER;
        }
    }

    /**
     * programmer - assigned globally unique string identifier
     */
    private final String id;

    /**
     * key for obtaining localized name from property resource bundle
     */
    private String localizationKey;

    public String getId() {
        return id;
    }

    public String getLocalizedName(Context ctx) {
        return Configurator.get().getLocalizedString(localizationKey, ctx != null ? ctx.getUserLocale() : Locale.getDefault());
    }

    public String getLocalizationKey() {
        return localizationKey;
    }

    public void setLocalizationKey(String key) {
        this.localizationKey = key;
    }

    @Override
    public String toString() {
        return id;
    }

    @Override
    public int hashCode() {
        return id.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (!(obj instanceof ServerDescriptorBase))
            return false;
        ServerDescriptorBase other = (ServerDescriptorBase) obj;
        if (id == null) {
            if (other.id != null)
                return false;
        } else if (!id.equals(other.id))
            return false;
        return true;
    }


    public static void setLocalizationKeyRoot(String root, ServerDescriptorBase... descriptors){
        for (ServerDescriptorBase desc : descriptors){
            String oldKey = desc.getLocalizationKey();
            if (oldKey.contains(".")){
                desc.setLocalizationKey(root+oldKey.substring(oldKey.indexOf(".")));
            }

        }
    }
}
